package com.ase.springsecurity.service.impl;

import com.ase.springsecurity.entity.mongodb.UserMongoDB;
import com.ase.springsecurity.service.UserMongoDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author gyhstart
 * @create 2020/12/27 - 11:21
 **/

@Service
public class UserMongoDBServiceImpl implements UserMongoDBService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加用户
     *
     * @return
     */
    @Override
    public int saveMongoDB(UserMongoDB userMongoDB) {
        try {
            mongoTemplate.insert(userMongoDB, "user");
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * MongoDB 删除
     *
     * @param id
     */
    @Override
    public void removeMongoDB(int id) {
        Query query = new Query(new Criteria("id").is(id));
        mongoTemplate.remove(query, UserMongoDB.class);
    }

    /**
     * MongoDB 修改
     *
     * @param userMongoDB 通过用户id来更新名字
     */
    @Override
    public void updateMongoDB(UserMongoDB userMongoDB) {
        Query query = new Query(new Criteria("id").is(userMongoDB.getId()));
        Update update = new Update().set("name", userMongoDB.getName());
        mongoTemplate.updateMulti(query, update, UserMongoDB.class);
    }

    @Override
    public List<UserMongoDB> findMongoDB() {
        return mongoTemplate.findAll(UserMongoDB.class);
    }
}
